package com.cg.configer;
import cn.hutool.json.JSONUtil;
import com.cg.Exception.CommonErrorCode;
import com.cg.Exception.MyException;
import com.cg.result.ResultBase;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import java.text.SimpleDateFormat;
import java.util.Date;
@ControllerAdvice
@Slf4j
public class MyExceptionController {
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor( Date.class, new CustomDateEditor (dateFormat, false));
    }

    //重新修改了异常响应
    @ExceptionHandler(MyException.class)
    public Object handleException(MyException ex, HttpServletRequest request,
                                  HttpServletResponse response) {
        return errorResult(ex.getMessage(), CommonErrorCode.BUSINESS_ERROR, response);
    }
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return errorResult(e.getMessage(), CommonErrorCode.UNKNOWN_ERROR, response);
    }
    private Object errorResult(String messageStr, CommonErrorCode errorCode,
                               HttpServletResponse response) {
        log.warn("业务异常：{}", messageStr);
        try {
            //为了统一数据格式
            ResultBase resultBase = ResultBase.fail();
            resultBase.setMessage(messageStr);
            resultBase.setCode(errorCode);
            String resultJson = JSONUtil.toJsonStr(resultBase);
            response.setContentType( MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(resultJson);
        } catch (Exception e1) {
            log.error("未知异常：", e1);
        }
        return null;
    }

}
